#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdbool.h>

#define SIZE 1024
#define MAX_ARGC 64
#define SEP " "

char* argv[SIZE];
char env[SIZE];
char pwd[SIZE];
int lastcode = 0;

char* HOME()
{
    char* home = getenv("HOME");
    if(home == NULL) return "None";
    else return home;
}

const char* USER()
{
    char* user = getenv("USER");
    if(user == NULL) return "None";
    else return user;
}

const char* HOSTNAME()
{
    char* hostname = getenv("HOSTNAME");
    if(hostname == NULL) return "None";
    else return hostname;
}

const char* PWD()
{
    char* pwd = getenv("PWD");
    if(pwd == NULL) return "None";
    else return pwd;
}

int Interactive(char in[],int size)
{
    printf("[%s@%s%s]$",USER(),HOSTNAME(),PWD());
    //开始输入命令行
    fgets(in,size,stdin);
    //取出最后的'\n’
    in[strlen(in)-1] = 0;
    return strlen(in);
}

void Split(char in[])
{
    int i = 0;
    argv[i++] = strtok(in,SEP);
    while(argv[i++] = strtok(NULL,SEP));
    if(strcmp(argv[0],"ls") == 0)
    {
        argv[i-1] = (char*)"--color";
        argv[i] = NULL;
    }
    
}

int Bulidcmd()
{
    int ret = 0;
    //ret 为0表示非内建命令，ret为1表示内建命令
    if(strcmp("cd",argv[0]) == 0)
    {
        ret = 1;
        char* target = argv[1];
        if(target == NULL) target = HOME();
        chdir(target);
        char temp[SIZE];
        getcwd(temp,SIZE);
        int result = snprintf(pwd,SIZE,"PWD=%s",temp);
        if(result<0)
        {
            perror("snprintf()");
            exit(1);
        }
        else if(result>=SIZE)
        {
            fprintf(stderr,"error");
            exit(1);
        }
        putenv(pwd);
    }
    else if(strcmp("export",argv[0]) == 0)
    {
        ret = 0;
        if(argv[1])
        {
            strcpy(env,argv[1]);
            putenv(env);
        }

    }
    else if(strcmp("echo",argv[0]) == 0)
    {
        ret = 1;
        if(argv[1] == NULL)
        {
            printf("\n");
        }
        else
        {
            if(argv[1][0] == '$')
            {
                if(argv[1][1] == '?')
                {
                    printf("%d\n",lastcode);
                    lastcode = 0;
                }
                else
                {
                    char* e = getenv(argv[1]+1);
                    if(e) printf("%s\n",e);
                }
            }
            else
            {
                printf("%s\n",argv[1]);
            }
        }
    }
    return ret;
}

void Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        //让子进程执行
        execvp(argv[0],argv);
        exit(1);
    }
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid == id) lastcode = WEXITSTATUS(status);
}

int main()
{
    while(true)
    {
        //1.提供用户的交互界面,并获取用户输入的命令字串
        char commandline[SIZE];
        int n = Interactive(commandline,SIZE);
        if(n == 0) continue;
        //2.对字符串进行分割
        Split(commandline);
        //3.处理内建命令
        n = Bulidcmd();
        if(n) continue;
        //执行非自建命令
        Execute();
    }
    return 0;
}
